package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.*;
import com.itheima.dao.BlogSortMapper;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Blog;
import com.itheima.pojo.BlogSort;
import com.itheima.pojo.Tag;
import com.itheima.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author xuchangshuo
 * @date 2020/8/5 16:41
 */


import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private BlogSortMapper blogSortMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private BlogTagMapper blogTagMapper;


    @Override
    public Blog getBlogByUid(String uid) {
        Blog blog = blogMapper.selectByPrimaryKey(uid);
        return blog;
    }

    @Override
    public int getBlogPraiseCountByUid(String uid) {
        Integer count = commentMapper.getBlogPraiseCountByUid(uid);
        return count;
    }

    //获取博客类型
    @Override
    public String getBlogTypeByBlogUid(String blogUid) {
        String blogType = blogMapper.getBlogTypeByBlogUid(blogUid);
        return blogType;
    }

    @Override
    public List<Blog> getSameBlogByBlogUid(String sortId) {
        List<Blog> sameBlogList = blogMapper.getSameBlogByBlogUid(sortId);
        return sameBlogList;
    }

    @Override
    public List<Blog> getSameBlogByTagUid(String tagUid) {
        List<Blog> sameBlogList = blogMapper.getSameBlogByTagUid(tagUid);
        return sameBlogList;
    }

    @Override
    public void praiseBlogByUid(String uid) {
        blogMapper.praiseBlogByUid(uid);
    }

    @Override
    @Transactional
    public void add(Map<String, Object> map) {
        Blog blog = JSON.parseObject(JSON.toJSONString(map), Blog.class);
        BlogSort blogSort = JSON.parseObject(JSON.toJSONString(map.get("blogSort")), BlogSort.class);
        List<Tag> tags = JSON.parseArray(JSON.toJSONString(map.get("tagList")), Tag.class);
        //todo 图片是否需要插入
//        JSON.parseArray(map.get(""));

        blogMapper.insertSelective(blog);
        if (tags != null) {
            for (Tag tag : tags) {
                tagMapper.insertSelective(tag);
            }
        }
        blogSortMapper.insertSelective(blogSort);

    }

    @Override
    @Transactional
    public void delete(Map<String, Object> blogVO) {
        Blog blog = JSON.parseObject(JSON.toJSONString(blogVO), Blog.class);
        BlogSort blogSort = JSON.parseObject(JSON.toJSONString(blogVO.get("blogSort")), BlogSort.class);
        List<Tag> tags = JSON.parseArray(JSON.toJSONString(blogVO.get("tagList")), Tag.class);
        //todo 图片是否需要删除
//        JSON.parseArray(map.get(""));

        blogMapper.delete(blog);
        if(tags != null){
            for (Tag tag : tags) {
                tagMapper.delete(tag);
            }
        }
        blogSortMapper.delete(blogSort);

    }

    @Override
    @Transactional
    public void deleteBatch(List<Map<String, Object>> blogVoList) {
        for (Map<String, Object> blogVo : blogVoList) {
            this.delete(blogVo);
        }
    }

    @Override
    @Transactional
    public void edit(Map<String, Object> blogVO) {
        Blog blog = JSON.parseObject(JSON.toJSONString(blogVO), Blog.class);
        BlogSort blogSort = JSON.parseObject(JSON.toJSONString(blogVO.get("blogSort")), BlogSort.class);
        List<Tag> tags = JSON.parseArray(JSON.toJSONString(blogVO.get("tagList")), Tag.class);
        System.out.println(blog.getUid());
        blogMapper.updateByPrimaryKeySelective(blog);
        blogSortMapper.updateByPrimaryKeySelective(blogSort);
        if(tags != null){
            for (Tag tag : tags) {
                tagMapper.updateByPrimaryKeySelective(tag);
            }
        }

    }

    @Override
    public PageResult<Blog> getList(Map<String, Object> blogVO) {
        //获取当前页
        Integer currentPage = (Integer) blogVO.get("currentPage");
        if (null == currentPage || currentPage < 0) {
            currentPage = 0;
        }
        //设置默认每页显示条数
        Integer pageSize = (Integer) blogVO.get("pageSize");
        if (null == pageSize || pageSize <= 0) {
            pageSize = 10;
        }
        PageHelper.startPage(currentPage, pageSize);
        Example example = this.createExample(blogVO);
        Page<Blog> pageList = (Page<Blog>) blogMapper.selectByExample(example);
        if (pageList == null) {
            throw new RuntimeException("博客不存在!");
        }
        List<Blog> blogList = pageList.getResult();
        if (blogList == null || blogList.size() <= 0) {
            throw new RuntimeException("博客不存在");
        }
        List<Tag> tagList = new ArrayList<>();
        blogList.forEach(blog -> {
            List<String> tagUidList = blogTagMapper.getTagUidList4BlogUid(blog.getUid());
            BlogSort blogSort = blogSortMapper.selectByPrimaryKey(blog.getBlogSortUid());
            blog.setBlogSort(blogSort);
            tagUidList.forEach(tagUid->{
                Tag tag = tagMapper.selectByPrimaryKey(tagUid);
                tagList.add(tag);
            });
            blog.setTagList(tagList);
        });
        PageResult<Blog> result = new PageResult<>();
        result.setTotal(pageList.getTotal());
        result.setSearchCount(true);
        result.setSize((long) pageList.getPageSize());
        result.setRecords(blogList);
        result.setCurrent((long) pageList.getPageNum());
        result.setOptimizeCountSql(true);
        return result;
    }

    @Override
    public Page<Blog> getBlogByLevel(Integer level, Long currentPage, Integer useSort) {
        PageHelper.startPage(currentPage.intValue(), 10);
        Example example = new Example(Blog.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("level", level);
        example.setOrderByClause("click_count DESC");
        Page<Blog> blogs = (Page<Blog>) blogMapper.selectByExample(example);
        return blogs;
    }


    @Override
    public Page<Blog> getBlogByTime(Long currentPage, Long pageSize) {
        PageHelper.startPage(currentPage.intValue(), 10);
        Example example = new Example(Blog.class);
        example.setOrderByClause("create_time DESC");
        Page<Blog> blogs = (Page<Blog>) blogMapper.selectByExample(example);
        for (Blog blog : blogs) {
            List<Tag> list = tagMapper.findTags(blog.getUid());
            BlogSort blogSort = blogSortMapper.selectByPrimaryKey(blog.getBlogSortUid());
            blog.setBlogSort(blogSort);
            blog.setTagList(list);
        }
        return blogs;
    }

    @Override
    public List<Blog> getHotBlog() {
        Example example = new Example(Blog.class);
        example.setOrderByClause("click_count DESC");
        List<Blog> blogs = blogMapper.selectByExample(example);
        for (Blog blog : blogs) {
            List<Tag> list = tagMapper.findTags(blog.getUid());
            BlogSort blogSort = blogSortMapper.selectByPrimaryKey(blog.getBlogSortUid());
            blog.setBlogSort(blogSort);
            blog.setTagList(list);
        }
        return blogs;
    }

    @Override
    public List<Tag> getHotTag() {
        Example example = new Example(Blog.class);
        example.setOrderByClause("click_count DESC");
        List<Tag> tags = tagMapper.selectByExample(example);
        return tags;
    }

    @Override
    public List<Blog> getNewBlog(Long currentPage, Long pageSize) {
        PageHelper.startPage(currentPage.intValue(), pageSize.byteValue());
        Example example = new Example(Blog.class);
        example.setOrderByClause("create_time DESC");
        Page<Blog> blogs = (Page<Blog>) blogMapper.selectByExample(example);
        for (Blog blog : blogs) {
            List<Tag> list = tagMapper.findTags(blog.getUid());
            BlogSort blogSort = blogSortMapper.selectByPrimaryKey(blog.getBlogSortUid());
            blog.setBlogSort(blogSort);
            blog.setTagList(list);
        }
        return blogs;
    }

    public List<Blog> getAll() {
        return blogMapper.selectAll();
    }

    //根据id查询单条数据
    @Override
    public Blog findById(String uid) {
        return blogMapper.selectByPrimaryKey(uid);
    }

    @Override
    public Page<Blog> getArticleByTagUid(String tagUid, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        PageHelper.startPage(currentPage, pageSize);
        //每条数据里面有三个对象
        //根据tagUid获取blog集合
        Page<Blog> blogs = (Page<Blog>) blogMapper.getBlogsByTagUid(tagUid);
        for (Blog blog : blogs) {
            //根据tagUid获取taglist
            List<Tag> tags = tagMapper.findTags(tagUid);
            //根据blogSortUid获取blogSort
            BlogSort blogSort = blogSortMapper.selectByPrimaryKey(blog.getBlogSortUid());
            blog.setTagList(tags);
            blog.setBlogSort(blogSort);
        }

        return blogs;
    }

    //从前端取出数据，存入blog中
    private Blog getBlog(Map<String, Object> map) {
        if (map != null) {
            //取出数据
            String adminUid = (String) map.get("adminUid");
            String articlesPart = (String) map.get("articlesPart");
            String author = (String) map.get("author");
            String blogSortUid = (String) map.get("blogSortUid");
            String content = (String) map.get("content");
            String fileUid = (String) map.get("fileUid");
            String isOriginal = (String) map.get("isOriginal");
            String isPublish = (String) map.get("isPublish");
            int level = Integer.parseInt((String) map.get("level"));
            long sort = Long.parseLong((String) map.get("sort"));
            int startComment = Integer.parseInt((String) map.get("startComment"));
            int status = Integer.parseInt((String) map.get("status"));
            String summary = (String) map.get("summary");
            String tagUid = (String) map.get("tagUid");
            String title = (String) map.get("title");
            String uid = (String) map.get("uid");

            //存入数据
            Blog blog = new Blog();
            if (adminUid != null) {
                blog.setAdminUid(adminUid);
            }
            if (articlesPart != null) {
                blog.setArticlesPart(articlesPart);
            }
            if(author != null){
                blog.setAuthor(author);
            }
            if(blogSortUid != null){
                blog.setBlogSortUid(blogSortUid);
            }
            if(content != null){
                blog.setContent(content);
            }
            if(fileUid != null){
                blog.setFileUid(fileUid);
            }
            if(isOriginal != null){
                blog.setIsOriginal(isOriginal);
            }
            if(isPublish != null){
                blog.setIsPublish(isPublish);
            }

            if(summary != null){
                blog.setSummary(summary);
            }
            if(tagUid != null){
                blog.setTagUid(tagUid);
            }
            if(title != null){
                blog.setTitle(title);
            }
            if(uid != null){
                blog.setUid(uid);
            }
            blog.setLevel(level);
            blog.setStartComment(startComment);
            blog.setStatus(status);
            blog.setSort(sort);
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());

            return blog;

        } else {
            return null;
        }
    }

    //构建查询对象
    private Example createExample (Map<String,Object> blogVo){
        Example example = new Example(Blog.class);
        Example.Criteria criteria = example.createCriteria();
        if(blogVo != null){
            // uid
            if(blogVo.get("uid")!=null || !"".equals(blogVo.get("uid"))){
                criteria.andEqualTo("uid",blogVo.get("uid"));
            }
            //title
            if(blogVo.get("title")!=null && !"".equals(blogVo.get("title"))){
                criteria.andLike("title","%"+blogVo.get("name")+"%");
            }
            //summary
            if(blogVo.get("summary")!=null && !"".equals(blogVo.get("summary"))){
                criteria.andLike("summary","%"+blogVo.get("summary")+"%");
            }
            //content
            if(blogVo.get("content")!=null && !"".equals(blogVo.get("content"))){
                criteria.andLike("content","%"+blogVo.get("content")+"%");
            }
            //keyword
            if (blogVo.get("keyword") != null && !"".equals(blogVo.get("keyword"))) {
                criteria.andLike("keyword", "%" + blogVo.get("keyword") + "%");
            }
            //tagUid
            if(blogVo.get("tagUid")!=null && !"".equals(blogVo.get("tagUid"))){
                criteria.andEqualTo("tagUid",blogVo.get("tagUid"));
            }
            //fileUid
            if(blogVo.get("fileUid")!=null ){
                criteria.andEqualTo("fileUid",blogVo.get("fileUid"));
            }
            //status
            if(blogVo.get("status")!=null ){
                criteria.andEqualTo("status",blogVo.get("status"));
            }
            //adminUid
            if(blogVo.get("adminUid")!=null ){
                criteria.andEqualTo("adminUid",blogVo.get("adminUid"));
            }
            //is_original
            if(blogVo.get("isOriginal")!=null && !"".equals(blogVo.get("isOriginal"))){
                criteria.andEqualTo("isOriginal",blogVo.get("isOriginal"));
            }
            //author
            if(blogVo.get("author")!=null && !"".equals(blogVo.get("author"))){
                criteria.andLike("author","%"+blogVo.get("author")+"%");
            }
            //articlesPart
            if(blogVo.get("articlesPart")!=null && !"".equals(blogVo.get("articlesPart"))){
                criteria.andLike("articlesPart","%"+blogVo.get("articlesPart")+"%");
            }
            //blogSortUid
            if(blogVo.get("blogSortUid")!=null && !"".equals(blogVo.get("blogSortUid"))){
                criteria.andEqualTo("blogSortUid",blogVo.get("blogSortUid"));
            }
            //level
            if(blogVo.get("level")!=null && !"".equals(blogVo.get("level"))){
                criteria.andEqualTo("level",blogVo.get("level"));
            }
            //levelKeyword
            if(blogVo.get("levelKeyword")!=null && !"".equals(blogVo.get("levelKeyword")) ){
                criteria.andEqualTo("level",blogVo.get("level"));
            }

            //is_publish
            if(blogVo.get("isPublish")!=null && !"".equals(blogVo.get("isPublish")) ){
                criteria.andEqualTo("isPublish",blogVo.get("isPublish"));
            }

        }
        return example;
    }


}
